package com.jlf.starter.advice.reactive.util;

import com.jlf.core.annotation.restful.RestfulToolkit;
import com.jlf.core.annotation.restful.controller.RestfulController;
import com.jlf.core.output.ResultWrapper;
import org.springframework.core.MethodParameter;
import org.springframework.web.reactive.HandlerResult;

import java.util.Collection;

/**
 * 输出的辅助工具
 *
 * @author wujr
 * 2023/8/2
 * @version 1.0
 * 【变更历史】
 * [wujr 2023/8/2 1.0 新增]
 */
public class OutputTool {
    public static boolean isSupported(HandlerResult result){
        MethodParameter methodParameter = result.getReturnTypeSource();
        Class<?> controllerClass = methodParameter.getExecutable().getDeclaringClass();
        boolean apiPresent = controllerClass.isAnnotationPresent(RestfulController.class);
        if (apiPresent){
            RestfulController apiController = controllerClass.getAnnotation(RestfulController.class);
            if(!apiController.outputWrapper()){
                // 该接口控制器都需要不需要定制包装输出，统一为json格式
                return true;
            }
            return RestfulToolkit.isProduceJson(methodParameter);
        }

//        return controllerClass.isAssignableFrom(ExceptionAdvice.class);
        return false;
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    public static ResultWrapper wrapResult(Object body) {
        // 如果已经是 ResultWrapper 类型，则直接返回
        if (body instanceof ResultWrapper) {
            return (ResultWrapper) body;
        }
        // 如果不是，则包装成 ResultWrapper 类型
        if (body == null){
            return ResultWrapper.ok(body);
        }
        if (body.getClass().isArray()){
            // 这是数组，需要转换
            Object[] array = (Object[])body;
            return ResultWrapper.ok(array);
        }else if (body instanceof Collection collection){
            return ResultWrapper.ok(collection);
        }
        return ResultWrapper.ok(body);
    }
}
